<?php
/**
* 微信公众号
*/
class mc_weixin extends ms_base
{
	private $roleObj = null;

	private $msgObj = null;

	function __construct($role)
	{
		parent::__construct();
		$this->roleObj = $role;
	}

	//真实性验证
	public function verify()
	{
		return $this->checkSignature();
	}

	//微信信息接收
	function response()
	{
		//消息验证通过
		if($this->verify()) {
			//微信服务器首次验证
			if($_GET['echostr']) {
				echo $_GET['echostr'];
				exit;
			}
			//消息接送
			$postStr = $GLOBALS['HTTP_RAW_POST_DATA'];
			if (!empty($postStr)) {
				//if(DEBUG) {
				//	log_write('weixin_debug', request_uri()."\n".$postStr);
				//}
				//微信信息已加密，需要先解密
				if(_get('encrypt_type')=='aes') {
					$postStr = $this->msgDecode($postStr);
					if(DEBUG) {
						log_write('weixin_debug', "DECODE\n".$postStr);
					}
					if(is_object($postStr)) {
						//加密信息解密失败
						$msg = array(
							'msg' => 'POST_DATA DECODE ERROR[code:'.$postStr->erron().']',
							'url' => $_SERVER['REQUEST_URI'],
						);
						log_write('weixin', $msg);
						return;
					}
				}
				$this->msgObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
				//微信信息接受类做详细处理
				$this->process();
			} else {
				//用户发送的信息为空
				$msg = array(
					'msg' => 'POST_DATA EMPTY',
					'url' => $_SERVER['REQUEST_URI'],
				);
				log_write('weixin', $msg);
			}
		} else {
			//参数验证失败
			$msg = array(
				'msg' => 'verify invalid',
				'url' => $_SERVER['REQUEST_URI'],
			);
			//写入日志
			log_write('weixin', $msg);
		}
	}

	//针对用户回复信息进行处理
	function process()
	{
		if (! $this->msgObj) {
			return;
		}
		//GBK用户转码
		//if(strtolower(G('charset')) != 'utf-8' && $this->msgObj->Content) {
			//log_write('weixin_debug_tmp',serialize($this->msgObj));
			//$this->msgObj->Content = charset_convert($this->msgObj->Content, 'utf-8', G('charset'));
			//if(DEBUG) log_write('weixin_debug', "UTF-8 TO ".G('charset')."\n======{$this->msgObj->Content}\n======");
		//}

		//实例化模型管理类
		$cmd_manage = new mc_weixin_cmd_manage();
		//执行指令
		$cmd_manage->run($this->roleObj, $this->msgObj);
	}

	private function msgDecode($postStr)
	{
		if(!class_exists('WXBizMsgCrypt')) {
            require_once MUDDER_ROOT.'api'.DS.'third_party'.DS.'weixin'.DS.'wxBizMsgCrypt.php';
        }

		$msg = '';
		$msg_sign = _get('msg_signature');
		$timeStamp = _get('timestamp');
		$nonce = _get('nonce');

		$pc = new WXBizMsgCrypt($this->roleObj->token, 
			$this->roleObj->config->encode_key, 
			$this->roleObj->appid
		);
		$errCode = $pc->decryptMsg($msg_sign, $timeStamp, $nonce, $postStr, $msg);
		if ($errCode == 0) {
			return $msg;
		} else {
            $tmp = new ms_base;
            $tmp->add_error("微信信息解密失败！[code:{$errCode}]", $errCode);
            return $tmp;
		}

//_get('msg_signature'),_get('timestamp'),_get('nonce'),$postStr;

	}

	//字段参数验证
	private function checkSignature()
	{
		$signature 	= $_GET["signature"];
		$timestamp 	= $_GET["timestamp"];
		$nonce 		= $_GET["nonce"];

		$tmpArr = array($this->roleObj->token, $timestamp, $nonce);
		sort($tmpArr, SORT_STRING);
		$tmpStr = implode( $tmpArr );
		$tmpStr = sha1( $tmpStr );

		return $tmpStr == $signature;
	}
}